<?php
declare(strict_types=1);
namespace cms\wechat\api_controller;

use cms\wechat\model\PlatformModel;
use cms\wechat\queue\MessageJob;
use cms\wechat\service\AuthorizeService;
use cms\wechat\service\OfficialService;
use cms\wechat\service\PlatformService;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class ServerController
 * @package cms\wechat\api_controller
 * @Controller(prefix="api/wechat/server")
 */
class ServerController extends CommonController
{
    /**
     * 公众号服务类
     * @Inject()
     * @var OfficialService
     */
    protected OfficialService $officialService;

    /**
     * 开放平台服务类
     * @Inject()
     * @var PlatformService
     */
    protected PlatformService $platformService;

    /**
     * 公众号授权服务类
     * @Inject()
     * @var AuthorizeService
     */
    protected AuthorizeService $authorizeService;

    /**
     * @return mixed
     */
    public function official()
    {
        $id = (int) $this->request->input('id', 0);
        $official = $this->officialService->getDataById($id);
        if (!$official) {
            return $this->error('参数错误');
        }
        // 公众号应用
        $official_application = $this->officialService->initApplication($official);
        $official_application->server->push(function ($message) use ($official) {
            return 'ok';
        });
        return $official_application->server->serve()->getContent();
    }

    /**
     * @RequestMapping(path="platform")
     */
    public function platform()
    {
        $id = (int) $this->request->input('id', 0);
        $app_id = (string) $this->request->input('app_id', '');
        // 取得开放平台
        $platform = $this->platformService->getDataById($id);
        if (!$platform) {
            return $this->error('开放平台错误');
        }
        if ($app_id) {
            if (stripos($app_id, '/') !== false) {
                $app_id = substr($app_id, 1);
            }
            return $this->_officialServer($platform, $app_id);
        }
        return $this->_platformServer($platform);
    }


    /**
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \ReflectionException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     */
    protected function _platformServer(PlatformModel $platform)
    {
        //实例化应用
        $platform_application = $this->platformService->initApplication($platform);
        $platform_application->server->push(function ($message) {
            echo '开放平台事件：';
            var_dump($message);
        });
        return $platform_application->server->serve()->getContent();
    }

    protected function _officialServer(PlatformModel $platform, string $app_id)
    {
        // 取得授权信息
        $authorize = $this->authorizeService->model->where([
            ['app_id', '=', $app_id],
            ['platform_id', '=', $platform->id]
        ])->first();
        if (!$authorize) {
            return $this->error('开放平台授权错误');
        }
        // 实例化开放平台应用
        $platform_application = $this->platformService->initApplication($platform);
        // 实例化公众号应用
        $official_application = $platform_application->officialAccount($authorize->app_id, $authorize->refresh_token);
        $official_application->server->push(function ($message) use ($authorize) {
            // 投递进消息队列
            make(DriverFactory::class)->get('wechat')->push(new MessageJob($message));
            return '';
        });
        return $official_application->server->serve()->getContent();
    }
}